﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Data;
using System.IO;
using System.IO.Ports;
using System.Text;
using System.Windows.Forms;
using MapControl;
using MapControl.Misc;

namespace GPSMap
{
    public partial class ucGPSData : UserControl
    {
        public frmGPSTracking formMain;
        public bool isStartTestGPSData = false;
        private AxMapWinGIS.AxMap AxMap1;
        public ucGPSData(frmGPSTracking frm, ComPort comPort)
        {
            formMain = frm;
            InitializeComponent();
            //RefreshDB();
            formMain.mapControl.AxMap_MouseDownEvent += new AxMapWinGIS._DMapEvents_MouseDownEventHandler(AxMap_MouseDownEvent);
            AxMap1 = formMain.mapControl.AxMap1;
            dataGridViewGPSData.DataSource = GeneralClass.dbTestGPS;
            InitDataGridView();

            //objPort = comPort;
            GeneralClass.objPort.comPort_DataReceivedEventLog += new SerialDataReceivedEventHandler(comPort_DataReceivedLog);
            GeneralClass.objPort.comPort_DataReceivedEvent2 += new SerialDataReceivedEventHandler(comPort_DataReceived2);

        }

        private void ucGPSData_Load(object sender, EventArgs e)
        {
            //checkBoxFilter_CheckedChanged(null,null);
            if (GeneralClass.dbTestGPS.Rows.Count > 0)
                labelCount.Text = GeneralClass.dbTestGPS.Rows.Count.ToString();
        }

        

        /// <summary>
        /// 
        /// </summary>
        /// <param name="text"></param>
        delegate void SetTextCallback(int count);
        private void SetText(int count)
        {
            // InvokeRequired required compares the thread ID of the
            // calling thread to the thread ID of the creating thread.
            // If these threads are different, it returns true.
            if (this.dataGridViewGPSData.InvokeRequired)
            {
                SetTextCallback d = new SetTextCallback(SetText);
                this.Invoke(d, new object[] { count });
            }
            else
            {
                labelCount.Text = count.ToString();// dataGridViewGPSData.Rows.Count.ToString();
                if (count > 0)
                {
                    try
                    {
                        dataGridViewGPSData.CurrentCell = dataGridViewGPSData.Rows[count - 1].Cells[0];
                        dataGridViewGPSData.Rows[count - 1].Selected = true;
                    }
                    catch
                    {
                        dataGridViewGPSData.DataSource = GeneralClass.dbTestGPS;
                    }
                        
                }
            }
        }

        public void comPort_DataReceived2(object sender, SerialDataReceivedEventArgs e)
        {
            //foreach (string text in GeneralClass.objPort.ListMessages)
            //{
                //Nếu Msg không phải "NAME-ACK" thì mới reply NAME-ACK
                //if (!text.Contains(GeneralClass.objPort.ACK_MSG))
                //{
                    //Hiển thị kết quả lên datagridview
                    //Để tránh lỗi cross-thread dùng hàm delegate SetText
                    SetText(GeneralClass.dbTestGPS.Rows.Count);
                //}
            //}
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="text"></param>
        delegate void SetLogCallback(string log);
        private void SetLog(string log)
        {
            // InvokeRequired required compares the thread ID of the
            // calling thread to the thread ID of the creating thread.
            // If these threads are different, it returns true.
            if (this.listBoxLog.InvokeRequired)
            {
                SetLogCallback d = new SetLogCallback(SetLog);
                this.Invoke(d, new object[] { log });
            }
            else
            {
                listBoxLog.BeginUpdate();
                listBoxLog.Items.Add(log);
                listBoxLog.EndUpdate();
            }
        }

        public void comPort_DataReceivedLog(object sender, SerialDataReceivedEventArgs e)
        {
            //Hiển thị log
            SetLog(GeneralClass.objPort.ListMessages[GeneralClass.objPort.ListMessages.Count-1]);
        }

        private void InitDataGridView()
        {
            //formMain.mapControl.AxMap_MouseDownEvent += new AxMapXLib.CMapXEvents_MouseDownEventHandler(AxMap_MouseDownEvent);
            //formMain.mapControl.AxMap_DrawUserLayer += new AxMapXLib.CMapXEvents_DrawUserLayerEventHandler(AxMap_DrawUserLayer);

            dataGridViewGPSData.Columns[0].HeaderText = "Thời gian";
            dataGridViewGPSData.Columns[1].HeaderText = "Tên";
            dataGridViewGPSData.Columns[2].HeaderText = "Vĩ độ";
            dataGridViewGPSData.Columns[3].HeaderText = "Kinh độ";
            dataGridViewGPSData.Columns[4].HeaderText = "Độ cao";
            dataGridViewGPSData.Columns[5].HeaderText = "Tốc độ";
            dataGridViewGPSData.Columns[6].HeaderText = "Hướng";

            dataGridViewGPSData.Columns[0].Width = 115;
            dataGridViewGPSData.Columns[0].DefaultCellStyle.Format = "dd/MM/yyyy HH:mm:ss";
            dataGridViewGPSData.Columns[1].Width = 35;
            dataGridViewGPSData.Columns[1].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dataGridViewGPSData.Columns[2].Width = 55;
            dataGridViewGPSData.Columns[2].DefaultCellStyle.Format = "#.00000";
            dataGridViewGPSData.Columns[3].Width = 60;
            dataGridViewGPSData.Columns[3].DefaultCellStyle.Format = "#.00000";
            dataGridViewGPSData.Columns[4].Width = 48;
            dataGridViewGPSData.Columns[4].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            dataGridViewGPSData.Columns[5].Width = 49;
            dataGridViewGPSData.Columns[5].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            dataGridViewGPSData.Columns[6].Width = 41;
            dataGridViewGPSData.Columns[6].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;


        }

        public void AxMap_MouseDownEvent(object sender, AxMapWinGIS._DMapEvents_MouseDownEvent e)
        {
            //PointF pScreen = new PointF(e.x, e.y);
            //Graphics g = AxMap1.CreateGraphics();

            //if (e.button == 1)
            //{
            //    //for (int i = 0; i < GeneralClass.dbTestGPS.Rows.Count; i++)
            //    //{
            //    //    GPSPoint objGPS = GetGPSData(GeneralClass.dbTestGPS.Rows[i]);
            //    //    //Nếu click trúng vào vị trí GPS thì hiển thị form
            //    //    if (objGPS.HitTest(pScreen) == 0 &&
            //    //        AxMap1.CurrentTool == MapXLib.ToolConstants.miArrowTool)
            //    //    {
            //    //        if (dataGridViewGPSData != null)
            //    //            dataGridViewGPSData.Rows[i].Cells["name"].Selected = true;
            //    //    }
            //    //}

            //}
            //g.Dispose();
        }


        //private void frmTestGPSData_FormClosed(object sender, FormClosedEventArgs e)
        //{
        //    t.Enabled = false;
        //    formMain.mapControl.Refresh();
        //}

        private void btnReset_Click(object sender, EventArgs e)
        {
            if (GeneralClass.objPort.IsOpen())
            {
                MessageBox.Show("Đóng cổng COM trước mới xóa!");
                return;
            }
            formMain.DeleteAllData();
            labelCount.Text = GeneralClass.dbTestGPS.Rows.Count.ToString();
            dataGridViewGPSData.DataSource = GeneralClass.dbTestGPS;
        }

        private void dataGridViewGPSData_CurrentCellChanged(object sender, EventArgs e)
        {
            //if (GeneralClass.dbTestGPS.Rows.Count > 0)
            //{
            //    //Nếu không phải đang tạo dữ liệu test
            //    if (!isStartTestGPSData)
            //    {
            //        if (dataGridViewGPSData.CurrentRow != null)
            //        {
            //            //GeneralClass.currGPSData = GetGPSData(GeneralClass.dbTestGPS.Rows[dataGridViewGPSData.CurrentCell.RowIndex]);
                        
            //            //GeneralClass.currGPSData.DrawPlaneImage(g);
            //            //AxMap1.ZoomTo(AxMap1.Zoom, GeneralClass.currGPSData.LonGPS, GeneralClass.currGPSData.LatGPS);
            //            //GeneralClass.currGPSData.Draw(g, Color.Red);
            //            //AxMap1.Refresh();
            //        }
            //    }
            //}
        }

        //private int indexRow = 0;
        //public void OnTimerEvent(object source, EventArgs e)
        //{
        //    GPSPoint gpsdata = GeneralClass.GetGPSData(AxMap1, GeneralClass.dbTestGPS.Rows[indexRow]);
            
        //        dataGridViewGPSData.CurrentCell = dataGridViewGPSData.Rows[indexRow].Cells[0];
        //        dataGridViewGPSData.Rows[indexRow].Selected = true;
        //    char[] data = gpsdata.ConverToByteArray();
        //    char[] buff = GeneralClass.objPort.SendGPSData(data);
        //    indexRow++;

        //    //if (indexRow == 10)
        //        //t.Enabled = false;

        //    if (indexRow == GeneralClass.dbTestGPS.Rows.Count-1)
        //        indexRow = 0;
        //}

        //private Timer t = new Timer();
        //private void btnSendToComPort_Click(object sender, EventArgs e)
        //{
        //    if (dataGridViewGPSData.Rows.Count == 0)
        //    {
        //        MessageBox.Show("Không có dữ liệu test để truyền!");
        //        return;
        //    }

        //    if (!GeneralClass.objPort.IsOpen())
        //    {
        //        MessageBox.Show("Chưa mở cổng COM");
        //        return;
        //    }
        //    t.Interval = 1000;
        //    t.Enabled = true;
        //    t.Tick += new System.EventHandler(OnTimerEvent);
        //}

        private void dataGridViewGPSData_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            //if (GeneralClass.dbTestGPS.Rows.Count > 0)
            //{
                if (dataGridViewGPSData.CurrentRow != null)
                {
                    //GeneralClass.currGPSData = formMain.GetGPSData(GeneralClass.dbTestGPS.Rows[dataGridViewGPSData.CurrentCell.RowIndex]);
                    //AxMap1.ZoomTo(AxMap1.Zoom, GeneralClass.currGPSData.LonGPS, GeneralClass.currGPSData.LatGPS);

                    GPSPoint objPoint = GeneralClass.GetGPSData(AxMap1, GeneralClass.dbTestGPS.Rows[dataGridViewGPSData.CurrentCell.RowIndex]);
                    //AxMap1.ZoomTo(AxMap1.Zoom, objPoint.LonGPS, objPoint.LatGPS);
                    //formMain.mapControl.Refresh();
                    
                    Graphics g = AxMap1.CreateGraphics();
                    objPoint.Draw(g, Color.Red);
                }
            //}
        }

        private void btnViewLogs_Click(object sender, EventArgs e)
        {
            string viewfile = "viewlogs.txt";
            File.Copy(GeneralClass.LogsFile,viewfile,true);
            Process.Start("notepad.exe", viewfile);
        }
    }
}
